<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 助手</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- 添加代码高亮样式 -->
    <link href="https://cdn.jsdelivr.net/npm/highlight.js@11.7.0/styles/github-dark.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #3d4185;
            height: 100vh;
            margin: 0;
            padding: 20px;
        }
        .chat-container {
            height: calc(100vh - 40px);
            background: white;
            border-radius: 15px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        .history-panel {
            background: #f8f9fa;
            border-right: 1px solid #dee2e6;
            height: 100%;
            overflow-y: auto;
            padding: 15px;
        }
        .chat-panel {
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        .chat-messages {
            flex-grow: 1;
            overflow-y: auto;
            padding: 20px;
        }
        .chat-input {
            border-top: 1px solid #dee2e6;
            padding: 15px;
            background: white;
        }
        .message {
            margin-bottom: 15px;
            max-width: 80%;
        }
        .message.user {
            margin-left: auto;
        }
        .message.assistant {
            margin-right: auto;
        }
        .message-content {
            padding: 10px 15px;
            border-radius: 15px;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
        }
        .message.user .message-content {
            background: #6B73FF;
            color: white;
        }
        .message.assistant .message-content {
            background: #f8f9fa;
        }
        .history-item {
            padding: 10px 15px;
            margin-bottom: 10px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s;
        }
        .history-item:hover {
            background: #e9ecef;
        }
        .history-item.active {
            background: #6B73FF;
            color: white;
        }
        .typing {
            font-style: italic;
            color: #6c757d;
        }
        .btn-new-chat {
            width: 100%;
            margin-bottom: 15px;
        }
        /* Markdown样式 */
        .markdown-body {
            font-size: 14px;
            line-height: 1.6;
        }
        
        .markdown-body pre {
            background: #1e1e1e;
            border-radius: 8px;
            padding: 15px;
            margin: 10px 0;
        }
        
        .markdown-body code {
            font-family: Consolas, Monaco, 'Courier New', monospace;
            padding: 2px 4px;
            border-radius: 4px;
        }
        
        .markdown-body p {
            margin-bottom: 10px;
        }
        
        .markdown-body ul, .markdown-body ol {
            padding-left: 20px;
            margin-bottom: 10px;
        }
        
        .markdown-body table {
            border-collapse: collapse;
            margin: 10px 0;
            width: 100%;
        }
        
        .markdown-body table th,
        .markdown-body table td {
            border: 1px solid #ddd;
            padding: 8px;
        }
        
        .markdown-body img {
            max-width: 100%;
            border-radius: 4px;
        }
        
        .message.assistant .message-content {
            background: #fff;
            padding: 15px;
        }
        
        .copy-btn {
            position: absolute;
            right: 10px;
            top: 10px;
            padding: 4px 8px;
            font-size: 12px;
            color: #fff;
            background: rgba(0,0,0,0.3);
            border: none;
            border-radius: 4px;
            cursor: pointer;
            opacity: 0;
            transition: opacity 0.2s;
        }
        
        pre:hover .copy-btn {
            opacity: 1;
        }
        
        .copy-btn:hover {
            background: rgba(0,0,0,0.5);
        }
        
        /* 自定义滚动条样式 */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: rgba(0, 0, 0, 0.05);
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: rgba(107, 115, 255, 0.3);
            border-radius: 4px;
            transition: all 0.3s ease;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: rgba(107, 115, 255, 0.5);
        }
        
        /* 针对Firefox */
        * {
            scrollbar-width: thin;
            scrollbar-color: rgba(107, 115, 255, 0.3) rgba(0, 0, 0, 0.05);
        }
        
        /* 优化滚动行为 */
        .history-panel,
        .chat-messages {
            scroll-behavior: smooth;
            -webkit-overflow-scrolling: touch;
        }
        
        /* 按钮基础样式 */
        .btn {
            padding: 8px 16px;
            font-weight: 500;
            border-radius: 8px;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        /* 主要按钮样式 */
        .btn-primary {
            background: linear-gradient(135deg, #6B73FF 0%, #000DFF 100%);
            border: none;
            color: white;
            box-shadow: 0 4px 12px rgba(107, 115, 255, 0.2);
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(107, 115, 255, 0.3);
            background: linear-gradient(135deg, #000DFF 0%, #6B73FF 100%);
        }
        
        .btn-primary:active {
            transform: translateY(0);
            box-shadow: 0 2px 8px rgba(107, 115, 255, 0.2);
        }
        
        /* 新对话按钮样式 */
        .btn-new-chat {
            width: 100%;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            font-size: 14px;
            padding: 10px;
        }
        
        .btn-new-chat i {
            font-size: 16px;
            transition: transform 0.3s ease;
        }
        
        .btn-new-chat:hover i {
            transform: rotate(180deg);
        }
        
        /* 发送按钮样式 */
        .chat-input .btn {
            padding: 8px 20px;
            margin-left: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .chat-input .btn i {
            font-size: 16px;
            transition: transform 0.3s ease;
        }
        
        .chat-input .btn:hover i {
            transform: translateX(3px);
        }
        
        /* 输入框样式优化 */
        .chat-input .input-group {
            background: white;
            border-radius: 12px;
            padding: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }
        
        .chat-input textarea {
            border: 1px solid rgba(107, 115, 255, 0.2);
            border-radius: 8px !important;
            padding: 10px;
            resize: none;
            transition: all 0.3s ease;
        }
        
        .chat-input textarea:focus {
            border-color: #6B73FF;
            box-shadow: 0 0 0 3px rgba(107, 115, 255, 0.1);
        }
        
        /* 按钮内容加载动画 */
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .btn-loading {
            position: relative;
            color: transparent !important;
        }
        
        .btn-loading::after {
            content: '';
            position: absolute;
            left: 50%;
            top: 50%;
            width: 16px;
            height: 16px;
            margin: -8px 0 0 -8px;
            border: 2px solid white;
            border-top-color: transparent;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row chat-container">
            <!-- 历史会话面板 -->
            <div class="col-3 history-panel">
                <button class="btn btn-primary btn-new-chat" onclick="startNewChat()">
                    <i class="fas fa-plus"></i> 新对话
                </button>
                <div id="historyList"></div>
            </div>
            
            <!-- 聊天面板 -->
            <div class="col-9 chat-panel">
                <div id="chatMessages" class="chat-messages"></div>
                <div class="chat-input">
                    <div class="input-group">
                        <textarea id="messageInput" class="form-control" rows="2" placeholder="输入消息..."></textarea>
                        <button class="btn btn-primary" onclick="sendMessage()">
                            <i class="fas fa-paper-plane"></i> 发送
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加必要的JavaScript库 -->
    <script src="https://cdn.jsdelivr.net/npm/marked@4.0.0/marked.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/highlight.js@11.7.0/lib/core.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/highlight.js@11.7.0/lib/common.min.js"></script>
    
    <script>
        // 配置marked
        marked.setOptions({
            highlight: function(code, lang) {
                if (lang && hljs.getLanguage(lang)) {
                    try {
                        return hljs.highlight(code, { language: lang }).value;
                    } catch (e) {}
                }
                return code;
            },
            breaks: true,
            gfm: true
        });
        
        // 当前会话ID
        let currentSessionId = null;
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadHistory();
            startNewChat();
            
            // 监听回车键发送消息
            document.getElementById('messageInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });
        });
        
        // 加载历史会话
        function loadHistory() {
            const history = JSON.parse(localStorage.getItem('chatHistory') || '[]');
            const historyList = document.getElementById('historyList');
            historyList.innerHTML = history.map(session => `
                <div class="history-item ${session.id === currentSessionId ? 'active' : ''}" >
                    <div class="d-flex justify-content-between align-items-center">
                        <span onclick="loadSession('${session.id}')" style="flex-grow: 1">${session.title || '新对话'}</span>
                        <i class="fas fa-trash" onclick="deleteSession('${session.id}')" style="cursor: pointer; padding: 4px"></i>
                    </div>
                </div>
            `).join('');
        }
        
        // 开始新会话
        function startNewChat() {
            currentSessionId = Date.now().toString();
            const history = JSON.parse(localStorage.getItem('chatHistory') || '[]');
            history.unshift({
                id: currentSessionId,
                title: '新对话',
                messages: []
            });
            localStorage.setItem('chatHistory', JSON.stringify(history));
            loadHistory();
            document.getElementById('chatMessages').innerHTML = '';
        }
        
        // 加载会话
        function loadSession(sessionId) {
            currentSessionId = sessionId;
            const history = JSON.parse(localStorage.getItem('chatHistory') || '[]');
            const session = history.find(s => s.id === sessionId);
            if (session) {
                document.getElementById('chatMessages').innerHTML = session.messages.map(msg => createMessageElement(msg)).join('');
                addCopyButtons();
                loadHistory();
                scrollToBottom();
            }
        }
        
        // 创建消息元素
        function createMessageElement(message) {
            const content = message.role === 'assistant' 
                ? marked.parse(message.content)
                : message.content;
                
            return `
                <div class="message ${message.role}">
                    <div class="message-content ${message.role === 'assistant' ? 'markdown-body' : ''}">
                        ${content}
                    </div>
                </div>
            `;
        }
        
        // 更新会话历史
        function updateHistory(message) {
            const history = JSON.parse(localStorage.getItem('chatHistory') || '[]');
            const session = history.find(s => s.id === currentSessionId);
            if (session) {
                session.messages.push(message);
                // 更新会话标题
                if (session.messages.length === 2) {
                    session.title = session.messages[0].content.substring(0, 20) + '...';
                }
                localStorage.setItem('chatHistory', JSON.stringify(history));
                loadHistory();
            }
        }
        
        // 发送消息
        async function sendMessage() {
            const input = document.getElementById('messageInput');
            const content = input.value.trim();
            if (!content) return;
            
            // 清空输入框
            input.value = '';
            
            // 显示用户消息
            const userMessage = { role: 'user', content };
            document.getElementById('chatMessages').innerHTML += createMessageElement(userMessage);
            updateHistory(userMessage);
            scrollToBottom();
            
            try {
                // 获取历史消息
                const history = JSON.parse(localStorage.getItem('chatHistory') || '[]');
                const session = history.find(s => s.id === currentSessionId);
                const messages = session ? session.messages : [];
                
                // 创建AI回复的消息容器
                const aiMessageDiv = document.createElement('div');
                aiMessageDiv.className = 'message assistant';
                aiMessageDiv.innerHTML = '<div class="message-content typing">AI正在思考...</div>';
                document.getElementById('chatMessages').appendChild(aiMessageDiv);
                scrollToBottom();
                
                // 调用AI接口（使用流式响应）
                const response = await fetch('/api/ai/chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        messages: messages.map(msg => ({
                            role: msg.role,
                            content: msg.content
                        })),
                        stream: true
                    })
                });

                // 处理流式响应
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let aiMessage = { role: 'assistant', content: '' };
                
                while (true) {
                    const { value, done } = await reader.read();
                    if (done) break;
                    
                    // 解析SSE数据
                    const text = decoder.decode(value);
                    const lines = text.split('\n');
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.slice(6));
                                if (data.content) {
                                    aiMessage.content += data.content;
                                    aiMessageDiv.innerHTML = `
                                        <div class="message-content markdown-body">
                                            ${marked.parse(aiMessage.content)}
                                        </div>
                                    `;
                                    addCopyButtons();
                                    scrollToBottom();
                                }
                            } catch (e) {
                                console.error('Error parsing SSE data:', e);
                            }
                        }
                    }
                }
                
                // 更新历史记录
                updateHistory(aiMessage);
                
            } catch (error) {
                console.error('Error:', error);
                const errorDiv = document.createElement('div');
                errorDiv.className = 'message assistant';
                errorDiv.innerHTML = `<div class="message-content text-danger">发生错误: ${error.message}</div>`;
                document.getElementById('chatMessages').appendChild(errorDiv);
                scrollToBottom();
            }
        }
        
        // 滚动到底部
        function scrollToBottom() {
            const chatMessages = document.getElementById('chatMessages');
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
        
        // 添加代码复制功能
        function addCopyButtons() {
            document.querySelectorAll('pre').forEach(pre => {
                if (!pre.querySelector('.copy-btn')) {
                    const button = document.createElement('button');
                    button.className = 'copy-btn';
                    button.textContent = '复制';
                    button.onclick = async () => {
                        const code = pre.querySelector('code').innerText;
                        await navigator.clipboard.writeText(code);
                        button.textContent = '已复制!';
                        setTimeout(() => {
                            button.textContent = '复制';
                        }, 2000);
                    };
                    pre.style.position = 'relative';
                    pre.appendChild(button);
                }
            });
        }
        
        // 添加删除会话函数
        function deleteSession(sessionId) {
            const history = JSON.parse(localStorage.getItem('chatHistory') || '[]');
            const newHistory = history.filter(session => session.id !== sessionId);
            localStorage.setItem('chatHistory', JSON.stringify(newHistory));
            
            if (sessionId === currentSessionId) {
                currentSessionId = null;
                document.getElementById('chatMessages').innerHTML = '';
                if (newHistory.length > 0) {
                    loadSession(newHistory[0].id);
                }
            }
            
            loadHistory();
        }
    </script>
</body>
</html> 
</html> 